from django.shortcuts import render
from django.views import View
from apps.contents.models import GoodsChannel, ContentCategory


# Create your views here.

class IndexView(View):
    def get(self, request):
        # 商品分类字典容器
        categories = {}
        # 查询所有的37个频道(一级分类)
        # GoodsChannel.objects.all().order_by('sequence')
        channels = GoodsChannel.objects.order_by('group_id', 'sequence')
        # 遍历所有频道,取出每一个频道
        for channel in channels:
            # 通过频道数据关联的组取出对应的组号
            group_id = channel.group.id
            # 将group_id作为categories字段的key
            if group_id not in categories:  # 避免重复分组
                categories[group_id] = {'channels': [], 'sub_cats': []}

            # 获取当前频道的一级分类(一个频道对应一个一级分类)
            cat1 = channel.category
            # 添加每组中对应的频道数据
            categories[group_id]['channels'].append({
                "id": channel.id,
                "name": cat1.name,
                "url": channel.url,
            })

            # 添加每组中的二级和三级分类
            # 通过一级分类找到所有的二级分类
            for cat2 in cat1.subs.all():
                # 使用二级分类查询三级分类
                sub_cats = []
                for cat3 in cat2.subs.all():
                    sub_cats.append({
                        "id": cat3.id,
                        "name": cat3.name,
                    })
                categories[group_id]['sub_cats'].append({
                    "id": cat2.id,
                    "name": cat2.name,
                    "sub_cats": sub_cats,
                })
        # 查询所有首页广告数据
        contents = {}
        # 查询官高所有类别,遍历出每一种广告
        content_categories = ContentCategory.objects.all()
        for content_cat in content_categories:
            # 遍历取出每种广告内容
            contents[content_cat.key] = content_cat.content_set.filter(status=True).order_by('sequence')


